package com.yeyaomai.dksns.flowis.servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.mapreduce.GroupByResults;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.yeyaomai.dksns.flowis.domain.AccessAnalysis;
import com.yeyaomai.dksns.flowis.domain.AccessDate;
import com.yeyaomai.dksns.flowis.domain.flowisdetail.FlowisQueryOrder;
import com.yeyaomai.dksns.flowis.service.AccessAnalysisService;
import com.yeyaomai.dksns.flowis.service.DownExcelService;
import com.yeyaomai.dksns.flowis.service.FlowisQueryService;
import com.yeyaomai.dksns.flowis.util.VelocityToolDateUtils;

@Controller
@RequestMapping("/access/*")
public class AccessAnalysisController {

	@Autowired
	private AccessAnalysisService accessAnalysisService;
	@Autowired
	FlowisQueryService flowisQueryService;
	@Autowired
	DownExcelService  downExcelService;

	@RequestMapping(method = RequestMethod.GET, value = "/analysis")
	public String accessAnalysis(HttpServletRequest request,
			HttpServletResponse httpResponse, FlowisQueryOrder order,
			ModelMap modelMap) {

		order.setStartTime(request.getParameter("startTime") != null ? request
				.getParameter("startTime") : VelocityToolDateUtils.getDay(0));
		order.setEndTime(request.getParameter("endTime") != null ? request
				.getParameter("endTime") : VelocityToolDateUtils.getDay(0));
		String type = request.getParameter("type") != null ? request.getParameter("type") : "1";
		String page = request.getParameter("page") !=null ? request.getParameter("page") : "";
		order.setUrl(request.getParameter("url") !=null ? request.getParameter("url") : "");
		order.setPage(page);
		
		Page<AccessAnalysis> accessAnalysisPage  = accessAnalysisService.getSplit(order);
		
		modelMap.addAttribute("accessAnalysisPage", accessAnalysisPage);
		modelMap.addAttribute("order", order);
		modelMap.addAttribute("type", type);
		if(page.equals("enter")) 	return "page-enter";
		else if(page.equals("out"))	return "page-out"; 
		else return "respondents-page";
		
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "/remain")
	@SuppressWarnings("unchecked")
	public String remain(ModelMap modelMap){
		
		String st = VelocityToolDateUtils.getMinute(-15);
		String et = VelocityToolDateUtils.getMinute(0);
		
		List<AccessDate> accessDateList = new ArrayList<AccessDate>();
		
		GroupByResults<AccessDate> accesss  = accessAnalysisService.getAccessAnalysis(st, et);
		
		for (AccessDate access : accesss) {
			accessDateList.add(access);
		}
		Collections.sort(accessDateList);
		
		Map<String, Integer> map = new HashMap<String, Integer>();
		map = flowisQueryService.getDateByOnlineCount(new Date());
		modelMap.addAttribute("pv", map.get("pv"));
		modelMap.addAttribute("ip", map.get("ip"));
		modelMap.addAttribute("accessDateList", accessDateList);
		return "remain-page"; 
	}
	
	
	//受访分析报表下载
	@RequestMapping(value="downAnalysis")
	public void downLately(HttpServletRequest request,HttpServletResponse response,
			FlowisQueryOrder order) throws UnsupportedEncodingException {
			
		String st = request.getParameter("startTime") != null ? request
				.getParameter("startTime") : VelocityToolDateUtils.getDay(0);
		String et = request.getParameter("endTime") != null ? request
				.getParameter("endTime") : VelocityToolDateUtils.getDay(0);
		String page = request.getParameter("page") !=null ? request.getParameter("page") : "";
		String url = page == "source" ? request.getParameter("url") : "";
		
		List<AccessAnalysis>  accessList =	accessAnalysisService.getAccessAnalysisByDate(st, et, page, url);
		
		String title ="";
	    if (page.equals("enter"))    title = "站内入口("+order.getStartTime()+"至"+order.getEndTime()+")";
	    else if (page.equals("out"))    title = "站内出口("+order.getStartTime()+"至"+order.getEndTime()+")";
	    else   title = "受访页面("+order.getStartTime()+"至"+order.getEndTime()+")";
	   
	    String newTitle = URLEncoder.encode(title, "UTF-8"); 

	    response.setContentType("application/vnd.ms-excel");
	    response.setHeader("Content-disposition", "attachment;filename=" + newTitle+".xls");   

	    List<String>  heads  =new ArrayList<String>();
	    if (page.equals("enter")) {
	    	heads.add("入口页面"); heads.add("进入次数");
	    } else if (page.equals("out")){
	    	heads.add("出口页面"); heads.add("离开次数");
	    }else {
	    	 heads.add("受访页面"); heads.add("浏览次数");
	    }
	    heads.add("人均浏览次数");
	    heads.add("平均停留时间（秒）");
	    heads.add("跳出率（%）");
	    
	    List<String> pros =new ArrayList<String>();
	    pros.add("access_url"); 
	    if (page.equals("enter"))  pros.add("enterNumber");
	    else if (page.equals("out"))  pros.add("outNumber");
	    else pros.add("browseNumber");
	    pros.add("pcBrowseNumber");
	    pros.add("aveStoptime");
	    pros.add("bounceRate");
	    
	    try {
	    	downExcelService.exportExcel(title, heads, accessList, response.getOutputStream(), pros);
	    } catch (IOException e) {
	    	e.printStackTrace();
	    }
	}
		
	
}
